//
//  VideoDetailViewController.m
//  taishan
//
//  Created by mac on 2019/4/15.
//  Copyright © 2019年 jznrj. All rights reserved.
//

#import "VideoDetailViewController.h"
#import <MJRefresh.h>
#import <Masonry.h>
#import "ColorUtil.h"
#import "URLUtil.h"
#import "JZNRequestUtil.h"
#import <MJExtension.h>
#import "LoginDto.h"
#import <SJVideoPlayer.h>
#import "ActivityIndicatorView.h"
#import "VideoViewRecord.h"
#import "VideoNews.h"
#import "UIColor+JZNExtension.h"
#import "LoginDto.h"
#import <UIImageView+WebCache.h>
#import "PBFlatBarButtonItems.h"

const float titleSize = 16.0, contentSize = 13.0,dateSize = 10.0;
@interface VideoDetailViewController ()

@property(nonatomic, strong) SJVideoPlayer *videoPlayer;
@property(nonatomic, strong) ActivityIndicatorView *loadingProgressView;
@property(nonatomic) long learnTime;
@property(nonatomic) long startTime;
@property(nonatomic) long endTime;
@property(nonatomic,strong) NSDate *inPageTime;

@property(nonatomic,strong) UIScrollView *scrollView;
@property(nonatomic,strong) UILabel *titleLabel;
@property(nonatomic,strong) UIImageView *dateImageView;
@property(nonatomic,strong) UILabel *dateLabel;
@property(nonatomic,strong) UIImageView *viewCountImageView;
@property(nonatomic,strong) UILabel *viewCountLabel;
@property(nonatomic,strong) UIImageView *favouriteImageView;
@property(nonatomic,strong) UIImageView *downloadImageView;
@property(nonatomic,strong) UIImageView *shareImageView;
@property(nonatomic,strong) UILabel *remarkLabel;

@property(nonatomic,strong) NSDate *startViewDate;

@end

@implementation VideoDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"视频详情";
    UINavigationBar * bar = self.navigationController.navigationBar;
    UIImage *bgImage = [ColorUtil navigationBarColor:[ColorUtil titleColor] BarSize:bar.frame alphe:1.0];
    [bar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
    [bar setTintColor:[UIColor whiteColor]];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]}forState:UIControlStateNormal];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kill:) name:@"UIApplicationWillTerminateNotification" object:nil];
    
    UIBarButtonItem *back = [PBFlatBarButtonItems backBarButtonItemWithTarget:self selector:@selector(goBack)];
    [self.navigationItem setLeftBarButtonItem:back];
    
    self.startViewDate = [[NSDate alloc]init];
    self.learnTime = 0;
    self.inPageTime = [[NSDate alloc]init];
    [self addloadingView];
    [self postVideoRecord];
    
    self.tabBarController.tabBar.frame = CGRectMake(0, 0, 0, 0);
    self.tabBarController.tabBar.hidden = YES;
    [self initView];
    
}


- (void)dealloc {
   // 在控制器释放的时候，一定要设置placeholder为nil，要不会有placeholder缓存
//    SJVideoPlayer.update(^(SJVideoPlayerSettings * _Nonnull common) {
//        common.placeholder = nil;
//    });
    // TESTLog(@"%d - -[%@ %s]", (int)__LINE__, NSStringFromClass([self class]), sel_getName(_cmd));
}


//- (void)willMoveToParentViewController:(UIViewController*)parent{
//
//    [super didMoveToParentViewController:parent];
//    if(!parent){
//        [self goBack];
//    }
//
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void) viewWillAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [_videoPlayer vc_viewDidAppear];

    [self requestVideoDetail];
    self.navigationController.navigationBar.hidden = NO;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_videoPlayer vc_viewWillDisappear];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_videoPlayer vc_viewDidDisappear];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
-(void) addloadingView{
    
//    [self.view addSubview:self.loadingProgressView];
//    [self.loadingProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.center.equalTo(self.view);
//    }];
//    [self.loadingProgressView startAnimating];
}
-(void) requestVideoList {
}
-(void) requestVideoDetail {
    NSString *url = [NSString stringWithFormat:@"%@/videoViewRecord/findVideoNewsAndRecord" ,[URLUtil hostName]];
    
    NSString *loginDtoJson = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
    LoginDto *loginDto = [LoginDto mj_objectWithKeyValues:loginDtoJson];
    
    NSDictionary *params = @{@"videoNewsId":_videoNewsId,@"userId":[NSString stringWithFormat:@"%d",loginDto.userId]};
    
    
    [JZNRequestUtil requestUrl:url requestParams:params success:^(DataResult *dataResult) {
        VideoViewRecord *videoViewsRecord = [VideoViewRecord mj_objectWithKeyValues:dataResult.data];
        NSString *videoUrl = videoViewsRecord.videoNewsUrl;
        if (![videoUrl hasPrefix:@"http"]) {
            videoUrl = [NSString stringWithFormat:@"%@%@",[URLUtil videoUrl],videoUrl];
        }

        self.videoPlayer.URLAsset = [[SJVideoPlayerURLAsset alloc] initWithURL:[NSURL URLWithString:videoUrl] startPosition:videoViewsRecord.endTime];
        self.videoPlayer.URLAsset.title = videoViewsRecord.videoNewsTitle;
       // self.videoPlayer.URLAsset.alwaysShowTitle = YES;
        self.videoPlayer.defaultEdgeControlLayer.hiddenBackButtonWhenOrientationIsPortrait = YES;
       // self.videoPlayer.defaultEdgeControlLayer.enableFilmEditing = YES;
        self.videoPlayer.pausedToKeepAppearState = YES;
        //self.videoPlayer.defaultEdgeControlLayer.generatePreviewImages = YES;
        self.videoPlayer.autoplayWhenSetNewAsset = YES;
        self.startTime = videoViewsRecord.endTime;
        
        self.titleLabel.text = videoViewsRecord.videoNewsTitle;
        self.remarkLabel.text = videoViewsRecord.remark;
        NSTimeInterval interval    = videoViewsRecord.uploadTime  / 1000.0;
        NSDate *uploadTime = [NSDate dateWithTimeIntervalSince1970:interval];
        NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
        fmt.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
        [fmt setDateStyle:NSDateFormatterMediumStyle];
        [fmt setTimeStyle:NSDateFormatterShortStyle];
        fmt.dateFormat = @"yyyy-MM-dd";
        self.dateLabel.text = [fmt stringFromDate:uploadTime];
        self.viewCountLabel.text = [NSString stringWithFormat:@"%li",videoViewsRecord.viewCount];
        [self requestVideoList];
        
    } failure:^(NSError *error) {
        
    }];
}

-(void) initView{
    _videoPlayer = [SJVideoPlayer player];
    [self.view addSubview:_videoPlayer.view];
    [_videoPlayer.view mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        else make.top.offset(0);
        make.leading.trailing.offset(0);
        make.height.equalTo(self->_videoPlayer.view.mas_width).multipliedBy(9 / 16.0f);
    }];
    if (![self.imageUrl hasPrefix:@"http"]) {
        self.imageUrl = [NSString stringWithFormat:@"%@/%@",[URLUtil hostName],self.imageUrl];
    }
    [_videoPlayer.presentView.placeholderImageView sd_setImageWithURL:[NSURL URLWithString:self.imageUrl]];
    
    self.scrollView = [[UIScrollView alloc]init];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.videoPlayer.view.mas_bottom);
        make.bottom.left.right.equalTo(self.view);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        }
    }];
    
    [self.scrollView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView).offset(10);
        make.width.equalTo(self.scrollView.mas_width).offset(-20);
        make.right.equalTo(self.view.mas_right).offset(-10);
    }];
    
    
    [self.scrollView addSubview:self.shareImageView];
    [self.shareImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.equalTo(@20);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(5);
        make.right.equalTo(self.view.mas_right).offset(-10);
    }];
    [self.scrollView addSubview:self.downloadImageView];
    [self.downloadImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.equalTo(@20);
        make.top.equalTo(self.shareImageView);
        make.right.equalTo(self.shareImageView.mas_left).offset(-15);
    }];
    
    [self.scrollView addSubview:self.favouriteImageView];
    [self.favouriteImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.equalTo(@20);
        make.top.equalTo(self.downloadImageView);
        make.right.equalTo(self.downloadImageView.mas_left).offset(-15);
    }];
    
    
    [self.scrollView addSubview:self.dateImageView];
    [self.dateImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scrollView).offset(10);
        make.width.height.equalTo(@20);
        make.centerY.equalTo(self.shareImageView);
    }];
    
    [self.scrollView addSubview:self.dateLabel];
    [self.dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@20);
        make.width.mas_greaterThanOrEqualTo(1);
        make.left.equalTo(self.dateImageView.mas_right);
        make.centerY.equalTo(self.shareImageView);
    }];
    
    [self.scrollView addSubview:self.viewCountImageView];
    [self.viewCountImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.dateLabel.mas_right).offset(2);
        make.width.height.equalTo(@20);
        make.centerY.equalTo(self.shareImageView);
    }];
    
    [self.scrollView addSubview:self.viewCountLabel];
    [self.viewCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@20);
        make.width.mas_greaterThanOrEqualTo(1);
        make.left.equalTo(self.viewCountImageView.mas_right);
        make.centerY.equalTo(self.shareImageView);
    }];
    
    [self.scrollView addSubview:self.remarkLabel];
    [self.remarkLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.shareImageView.mas_bottom).offset(8);
        make.width.equalTo(self.scrollView.mas_width).offset(-20);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.height.mas_greaterThanOrEqualTo(1);
    }];
    
    

}
- (void) kill:(UIApplication *)application {
    if (self.videoPlayer != nil) {
        NSTimeInterval time = self.videoPlayer.currentTime;
        NSDate *now = [[NSDate alloc]init];
        
        NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
        fmt.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
        [fmt setDateStyle:NSDateFormatterMediumStyle];
        [fmt setTimeStyle:NSDateFormatterShortStyle];
        fmt.dateFormat = @"yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";
        NSString *startViewTime = [fmt stringFromDate:self.inPageTime];
        NSString *nowTime = [fmt stringFromDate:now];
        self.learnTime = [now timeIntervalSince1970] - [self.inPageTime timeIntervalSince1970];
        NSString *loginDtoJson = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
        LoginDto *loginDto = [LoginDto mj_objectWithKeyValues:loginDtoJson];
        BOOL canGetScore = NO;
        if(_learnTime>300 || _learnTime >= _videoPlayer.duration) {
            canGetScore = YES;
        }
        NSDictionary *params = @{@"videoNewsId":_videoNewsId,
                                 @"departmentId":[NSString stringWithFormat:@"%d",loginDto.departmentId],
                                 @"userId":[NSString stringWithFormat:@"%d",loginDto.userId],
                                 @"endTime": [NSString stringWithFormat:@"%li",(long)time],
                                 @"startViewTime":startViewTime,
                                 @"endViewTime":nowTime,
                                 @"startTime":[NSString stringWithFormat:@"%li",self.startTime],
                                 @"learnTime":[NSString stringWithFormat:@"%li",self.learnTime],
                                 @"canGetScore": [NSNumber numberWithBool:canGetScore]
                                 };
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:params forKey:@"video_record"];
    }
    
}
-(void) postVideoRecord{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *videoRecord = [userDefaults objectForKey:@"video_record"];
    if (videoRecord!=nil) {
        NSString *url = [NSString stringWithFormat:@"%@/videoViewRecord/addVideoViewRecord" ,[URLUtil hostName]];
        [JZNRequestUtil requestUrl:url requestParams:videoRecord success:^(DataResult *dataResult) {
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults removeObjectForKey:@"video_record"];
        } failure:^(NSError *error) {
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:videoRecord forKey:@"video_record"];
        }];
    }
}


-(void) goBack{
    if (self.videoPlayer != nil) {
        NSString *url = [NSString stringWithFormat:@"%@/videoViewRecord/addVideoViewRecord" ,[URLUtil hostName]];
        NSTimeInterval time = self.videoPlayer.currentTime;
        NSDate *now = [[NSDate alloc]init];
        self.learnTime = [now timeIntervalSince1970] - [self.inPageTime timeIntervalSince1970];
        
        NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
        fmt.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
        [fmt setDateStyle:NSDateFormatterMediumStyle];
        [fmt setTimeStyle:NSDateFormatterShortStyle];
        fmt.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
        NSString *startViewTime = [fmt stringFromDate:self.inPageTime];
        NSString *nowTime = [fmt stringFromDate:now];
        
        NSString *loginDtoJson = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
        LoginDto *loginDto = [LoginDto mj_objectWithKeyValues:loginDtoJson];
        
        BOOL canGetScore = NO;
        if(_learnTime>300 || _learnTime > _videoPlayer.duration) {
           canGetScore = YES;
        }
        NSDictionary *params = @{@"videoNewsId":_videoNewsId,
                                @"departmentId":[NSString stringWithFormat:@"%d",loginDto.departmentId],
                                @"userId":[NSString stringWithFormat:@"%d",loginDto.userId],
                                @"endTime": [NSString stringWithFormat:@"%li",(long)time],
                                @"startViewTime":startViewTime,
                                @"endViewTime":nowTime,
                                @"startTime":[NSString stringWithFormat:@"%li",self.startTime],
                                @"learnTime":[NSString stringWithFormat:@"%li",self.learnTime],
                                @"canGetScore": [NSNumber numberWithBool:canGetScore]
                                };
        [JZNRequestUtil requestUrl:url requestParams:params success:^(DataResult *dataResult) {
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults removeObjectForKey:@"video_record"];
        } failure:^(NSError *error) {
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:params forKey:@"video_record"];
        }];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - tableview datasource
#pragma mark - initView
-(UILabel*) videoDetailLabel {
    UILabel *label = [[UILabel alloc]init];
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.numberOfLines = 0;
    return label;
}
-(UILabel*) titleLabel{
    if (!_titleLabel) {
        _titleLabel = [self videoDetailLabel];
        _titleLabel.font = [UIFont systemFontOfSize:titleSize];
        _titleLabel.textColor = [UIColor blackColor];
        
    }
    return _titleLabel;
}
-(UILabel*) remarkLabel{
    if (!_remarkLabel) {
        _remarkLabel = [self videoDetailLabel];
        _remarkLabel.font = [UIFont systemFontOfSize:contentSize];
        _remarkLabel.textColor = [UIColor colorWithHex:0x616161];
        
    }
    return _remarkLabel;
}

-(UILabel*) dateLabel{
    if(!_dateLabel){
        _dateLabel = [self videoDetailLabel];
        _dateLabel.font = [UIFont systemFontOfSize:dateSize];
        _dateLabel.textColor = [UIColor colorWithHex:0x919191];
    }
    return _dateLabel;
}
-(UILabel*) viewCountLabel{
    if(!_viewCountLabel){
        _viewCountLabel = [self videoDetailLabel];
        _viewCountLabel.font = [UIFont systemFontOfSize:dateSize];
        _viewCountLabel.textColor = [UIColor colorWithHex:0x919191];
    }
    return _viewCountLabel;
}
-(UIImageView*)videoDetailImageView{
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.backgroundColor = [UIColor clearColor];
    return imageView;
}

-(UIImageView*) dateImageView{
    if (!_dateImageView) {
        _dateImageView = [self videoDetailImageView];
        _dateImageView.image = [UIImage imageNamed:@"date.png"];
    }
    return _dateImageView;
}

-(UIImageView*) viewCountImageView{
    if (!_viewCountImageView) {
        _viewCountImageView = [self videoDetailImageView];
        _viewCountImageView.image = [UIImage imageNamed:@"record"];
    }
    return _viewCountImageView;
}
-(UIImageView*) favouriteImageView{
    if (!_favouriteImageView) {
        _favouriteImageView = [self videoDetailImageView];
     //   _favouriteImageView.image = [UIImage imageNamed:@"favorites.png"];
    }
    return _favouriteImageView;
}
-(UIImageView*) downloadImageView{
    if (!_downloadImageView) {
        _downloadImageView = [self videoDetailImageView];
     //   _downloadImageView.image = [UIImage imageNamed:@"download.png"];
    }
    return _downloadImageView;
}
-(UIImageView*) shareImageView{
    if (!_shareImageView) {
        _shareImageView = [self videoDetailImageView];
     //   _shareImageView.image = [UIImage imageNamed:@"share.png"];
    }
    return _shareImageView;
}

@end
